package com.abe.libcore.base.permission

import android.Manifest
import android.annotation.SuppressLint
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInstaller
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.text.TextUtils
import androidx.core.content.FileProvider
import androidx.fragment.app.FragmentActivity
import com.abe.libcore.utils.CommonUtils
import com.abe.libcore.utils.ThreadPoolUtils
import com.permissionx.guolindev.PermissionX
import com.permissionx.guolindev.request.ExplainScope
import java.io.File
import java.io.FileInputStream
import java.io.InputStream
import java.io.OutputStream

object PermissionUtils {
    //回调
    interface MultiPermissionCallback {
        fun onSuccess()
        fun onFail(failList: List<String>)
    }

    //回调
    interface PermissionCallback {
        fun onSuccess()
        fun onFail()
    }

    /**
     * 安装APK权限
     */
    fun installApk(activity: FragmentActivity?, fileName: String, authority: String) {
        if (activity == null || TextUtils.isEmpty(fileName)) return
        val file = File(fileName)
        installApk(activity, file, authority)
    }

    /**
     * 安装APK权限
     */
    fun installApk(activity: FragmentActivity, file: File, authority: String) {
        if (!file.exists()) return
        PermissionX.init(activity).permissions(Manifest.permission.REQUEST_INSTALL_PACKAGES)
            .onExplainRequestReason { scope, deniedList ->
                scope.showRequestReasonDialog(
                    deniedList, "应用安装需要您同意安装权限才能正常使用", "同意", "拒绝"
                )
            }.request { allGranted, grantedList, deniedList ->
                if (allGranted) {
                    val intent = Intent(Intent.ACTION_INSTALL_PACKAGE)
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                    val uri: Uri = getFileUri(activity, file, authority)
                    intent.setDataAndType(uri, "application/vnd.android.package-archive")
                    activity.startActivity(intent)
                }
            }
    }

    @SuppressLint("ObsoleteSdkInt")
    fun getFileUri(context: Context, file: File, authority: String): Uri {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return FileProvider.getUriForFile(
                context, authority, file
            )
        }
        return Uri.fromFile(file)
    }

    fun single(
        activity: FragmentActivity,
        callback: PermissionCallback?,
        permission: String,
        vararg defaultMsg: String?
    ) {
        PermissionX.init(activity).permissions(permission)
            .onExplainRequestReason { scope: ExplainScope, deniedList: List<String> ->
                val message =
                    if (defaultMsg.isNotEmpty()) defaultMsg[0] else "应用需要您同意以下权限才能正常使用"
                scope.showRequestReasonDialog(deniedList, message!!, "同意", "拒绝")
            }.request { allGranted: Boolean, grantedList: List<String>, deniedList: List<String> ->
                if (callback != null) {
                    if (allGranted) callback.onSuccess()
                    else callback.onFail()
                }
            }
    }

    fun multi(
        activity: FragmentActivity,
        callback: MultiPermissionCallback?,
        permissions: Array<String>,
        vararg defaultMsg: String?
    ) {
        PermissionX.init(activity).permissions(*permissions)
            .onExplainRequestReason { scope: ExplainScope, deniedList: List<String> ->
                CommonUtils.log("********************************111")
                val message =
                    if (defaultMsg.isNotEmpty()) defaultMsg[0] else "应用需要您同意以下权限才能正常使用"
                scope.showRequestReasonDialog(deniedList, message!!, "同意", "拒绝")
            }.request { allGranted: Boolean, grantedList: List<String>, deniedList: List<String> ->
                CommonUtils.log("********************************222:$allGranted")
                if (callback != null) {
                    if (allGranted) callback.onSuccess()
                    else callback.onFail(deniedList)
                }
            }
    }

    fun install(activity: FragmentActivity, file: File) {
        ThreadPoolUtils.execute {
            val mPackageManager: PackageManager = activity.packageManager
            val packageInstaller: PackageInstaller = mPackageManager.packageInstaller
            val params: PackageInstaller.SessionParams = PackageInstaller.SessionParams(
                PackageInstaller.SessionParams.MODE_FULL_INSTALL
            )
            val sessionId = packageInstaller.createSession(params)
            val session: PackageInstaller.Session =
                packageInstaller.openSession(sessionId)
            val ins: InputStream = FileInputStream(file);
            val out: OutputStream = session.openWrite("app", 0, -1)
            val buffer = ByteArray(1024 * 1024)
            var c: Int
            do {
                c = ins.read(buffer)
            } while (c >= -1)
            out.write(buffer, 0, c)
            session.fsync(out)
            session.commit(
                PendingIntent.getBroadcast(
                    activity,
                    0,
                    Intent("INSTALL_COMPLETE"),
                    PendingIntent.FLAG_IMMUTABLE
                ).intentSender
            )
        }
    }
}